import { rootState } from "@/store";
import { formattime } from "@/utils";
import React, { ReactElement, useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import Essayless from "./index.module.less";

export interface propsinterface {
  title: string;
  cover: string; //封面
  id: number;
  content: string;
  views: number; //浏览量
  pingluncount: number; //评论数,
  collectcount: number; //收藏数
  updateAt: string;
  iscollect: boolean; //当前用户是否收藏
}
interface oneassyinterface {
  oneassy: propsinterface;
}
interface oneassyinterface {
  children?: ReactElement<any, any>;
}
export default function Essay(props: oneassyinterface) {
  const {
    title,
    cover, //封面
    content,
    views, //浏览量
    pingluncount,
    collectcount,
    updateAt,
    id,
  } = props.oneassy;
  const { children } = props;
  const navigate = useNavigate();
  const wrap = useRef(null);
  //出现的动画
  const [isview, setIsview] = useState<boolean>(false);
  const {
    thumbdarr: { collectarr },
  } = useSelector((store: rootState) => ({
    thumbdarr: store.home.thumbdobj,
  }));
  useEffect(() => {
    const ob = new IntersectionObserver(
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          setIsview(true);
        } else {
          setIsview(false);
        }
      },
      { threshold: 0 }
    );
    if (wrap.current) {
      ob.observe(wrap.current as Element);
    }
  }, []);
  //进入文章详情页面
  const todetail = () => {
    navigate(`/essaydetail/${id}`);
  };

  return (
    <div
      ref={wrap}
      className={
        isview
          ? Essayless.oneessaywrap + " " + Essayless.active
          : Essayless.oneessaywrap
      }
    >
      <div className="imgwrap">
        <img src={cover} alt="" />
      </div>
      <div className="head">
        <div className="title">{title}</div>
        <span>{formattime(updateAt)}</span>
        {children && <div className="delete">{children}</div>}
      </div>
      <div className="content">{content.slice(0, 150)}</div>
      <div className="bottom">
        <span onClick={todetail}>开始阅读</span>
        <div className="right">
          <span>
            <span className="iconfont icon-liulanliang"></span>
            <div className="count"> {views}</div>
          </span>
          <span>
            <span
              className={
                collectarr.includes(id)
                  ? "iconfont icon-jushoucanggift active"
                  : "iconfont icon-jushoucanggift"
              }
            ></span>
            <span className="count">{collectcount}</span>
          </span>
          <span>
            <span className="iconfont icon-pinglun"></span>
            <span className="count"> {pingluncount}</span>
          </span>
        </div>
      </div>
    </div>
  );
}
